
package com.alcj.controller;

import com.alcj.common.constant.SysConstant;
import com.alcj.common.utils.CmnUtil;
import com.alcj.common.utils.MultipartFileUtil;
import com.alcj.model.User;
import com.alcj.service.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.swing.JOptionPane;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * @author :guofsh
 * @version :v1.0
 * @Package :com.alcj.controller
 * @Description :${TODO}(会员中心)
 * @date :2017/10/9
 */
@Controller
@RequestMapping("/userCenter")
public class UserCenterController {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    /**
     * @Author: guofsh
     * @Description:初期表示信息
     * @param request
     * @param model
     * @return String
     */
    @RequestMapping("/userInfo")
    public String init(HttpServletRequest request, Model model) {

        try {

            // 获取登录用户
            User sysUser = (User) request.getSession().getAttribute("User");

            // 获取登录用户判断用户Id跟用户类型是否为空
            if (CmnUtil.isEmpty(sysUser)){

                return SysConstant.INDEX_PAGE;

            }else
            {

                // 设定检索条件
                User paramInfo = new User();
                paramInfo.setUserid(sysUser.getUserid());

                User resultUser = userService.getUserInfo(paramInfo);

                // 初期设定信息
                if (!CmnUtil.isEmpty(resultUser)) {

                   model.addAttribute("baseUser", resultUser);
                } else {
                    model.addAttribute("baseUser", null);
                }
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("获取会员中心信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :",e);
            return SysConstant.ERROR_PAGE_500;
        }

       //跳转到会员中心页面
        return "userCenter";
    }
    /**
     * @Author: guofsh
     * @Description:验证原密码是否正确
     * @param request
     * @return boolean
     */
    @RequestMapping("/checkPassword")
    @ResponseBody
    public boolean checkPassword(HttpServletRequest request) {
        try {
            // 获取登录用户
            User sysUser = (User) request.getSession().getAttribute("User");

            //获取验证类型
            String tagItem = (String) request.getParameter("tagItem");

            //取得用户Id
            String userId = sysUser.getUserid().toString();

            boolean isSuccess = false;

            //判断验证类型
            if (!CmnUtil.isEmpty(tagItem)) {
                isSuccess = userService.checkPassword(userId,tagItem);
            }

            //返回验证结果
            return isSuccess;

        } catch (Exception e) {
            // 异常报错
            logger.error("校验验证码异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return false;
        }
    }

    /**
     * @Author: guofsh
     * @Description:获取表示信息
     * @param request
     * @return String
     */
    @RequestMapping("/getInfo")
    @ResponseBody
    public JSONObject getInfo(HttpServletRequest request) {
        JSONObject resultJson = new JSONObject();
        try {
            // 获取登录用户
            String userId = request.getSession().getAttribute("userId").toString();

            if (CmnUtil.isEmpty(userId)) {
                // 调用接口失败
                resultJson.put("status","1");
                resultJson.put("msg","获取参数错误");
            }

            // 设定检索条件
            User paramInfo = new User();
            paramInfo.setUserid(userId);

            User resultUser = userService.getUserInfo(paramInfo);

            // 初期设定信息
            if (!CmnUtil.isEmpty(resultUser)) {
                resultJson.put("status","0");
                resultJson.put("msg","操作成功");
                resultJson.put("data", JSONObject.toJSON(resultUser));
            } else {
                resultJson.put("status","1");
                resultJson.put("msg","用户不存在");
                resultJson.put("data", "");
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("获取用户中心信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :",e);
            resultJson.put("status","1");
            resultJson.put("msg","获取参数错误");
            return  resultJson;
        }

        return resultJson;
    }

    /**
     * @Author: guofsh
     * @Description:修改个人会员信息
     * @param request
     * @param model
     * @return String
     */
    @RequestMapping("/editFront")
    public String editFront(@RequestParam("verifyphoto") MultipartFile verifyphoto, HttpServletRequest request, RedirectAttributes model) {
        try {

            // 获取登录用户
            User sysUser = (User) request.getSession().getAttribute("User");

            // 获取登录用户判断用户Id跟用户类型是否为空
            if ((sysUser.getUserid() == null)&&(sysUser.getUsertype() == null)){

                return SysConstant.INDEX_PAGE;

            }
                //取得用户Id
                String sysUserId = sysUser.getUserid();

                //取得用户类型
                String sysUserType = sysUser.getUsertype();

                User paramInfo = new User();
                // 设定更新条件
                paramInfo.setUserid(sysUserId);
                // 设定更新内容
                //用户类型为个人或者代办时
                if (sysUserType.equals("0") || sysUserType.equals("2")) {

                    paramInfo.setRealname(request.getParameter("realname"));
                    paramInfo.setIdcardno(request.getParameter("idcard"));
                    paramInfo.setPaytype(request.getParameter("payment"));
                    paramInfo.setVerifyphoto(request.getParameter("" +
                            ""));


                }else
                {
                    paramInfo.setCompanyname(request.getParameter("companyname"));
                    paramInfo.setLegalname(request.getParameter("legalname"));
                    paramInfo.setIdcardno(request.getParameter("idcard"));
                    paramInfo.setSocialcredit(request.getParameter("socialcredit"));
                    if(verifyphoto.isEmpty()){

                    }else{
                        // 营业执照
                        String  uploadName = MultipartFileUtil.uploadFile(verifyphoto);
                        paramInfo.setVerifyphoto(uploadName);

                    }

                    paramInfo.setPaytype(request.getParameter("paytype"));
                }
            //共通设定内容
            paramInfo.setOptionid(sysUserId);
            Date date = new Date();
            paramInfo.setOptiontime(date);

            // 更新用户信息
            int result = userService.editUserInfo(paramInfo);

            // 初期设定信息
            if (result == 1) {
                //刷新页面
                return "redirect:/userCenter/userInfo";
            } else {
                return "提交失败";
           }

        } catch (Exception e) {
            // 异常报错
            logger.error("更新用户中心信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :",e);
            return SysConstant.ERROR_PAGE_500;
        }

       }

    /**
     * @Author: guofsh
     * @Description:修改密码手机号码
     * @param request
     * @param model
     * @return String
     */
    @RequestMapping("/editInfo")
    @ResponseBody
    public String editInfo(HttpServletRequest request, RedirectAttributes model) {
        try {

            // 获取登录用户
            User sysUser = (User) request.getSession().getAttribute("User");

            // 获取登录用户判断用户Id跟用户类型是否为空
            if ((sysUser.getUserid() == null)&&(sysUser.getUsertype() == null)){

                return SysConstant.INDEX_PAGE;

            }

            User paramInfo = new User();


            //取得用户Id
            String sysUserId = sysUser.getUserid().toString();

            //设定更新条件
            paramInfo.setUserid(sysUserId);

            //取得更新类型
            String tagType = (String) request.getParameter("tagType");

            //判断更新内容
            if (tagType.equals("1")){

            String userPwd = (String) request.getParameter("tagItem");
            paramInfo.setUserpwd(userPwd);
            }
            else {
             String telPhone = (String) request.getParameter("tagItem");
             paramInfo.setTelphone(telPhone);
            }

            //共通设定内容
            paramInfo.setOptionid(sysUserId);
            Date date = new Date();
            paramInfo.setOptiontime(date);

            // 更新用户信息
            int result = userService.editUserInfo(paramInfo);

            // 初期设定信息
            if (result == 1) {

                return "更新成功";

            } else {

                return SysConstant.ERROR_PAGE_500;
            }

        } catch (Exception e) {

            // 异常报错
            logger.error("更新用户中心信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :",e);
            return SysConstant.ERROR_PAGE_500;

        }

    }

    /**
     * @Author: guofsh
     * @Description:后台修改审核个人会员信息
     * @param request
     * @param model
     * @return String
     */
    @RequestMapping("/editRear")
    public String editRear(HttpServletRequest request, RedirectAttributes model, @RequestParam("userid") String userid,
                            @RequestParam("maxcar") int maxcar, @RequestParam("status") String status, @RequestParam("userlevel") String userlevel,
                            @RequestParam("viprebate") double viprebate, @RequestParam("delflag") String delflag) {
        try {
            // 获取登录用户
            User sysUser = (User) request.getSession().getAttribute("User");

            if (CmnUtil.isEmpty(sysUser)) {
                return SysConstant.LOGIN_PAGE;
            }

            User paramInfo = new User();
            // 设定更新条件
            paramInfo.setUserid(userid);
            // 设定更新内容
            paramInfo.setMaxcar(maxcar);
            paramInfo.setStatus(status);
            paramInfo.setUserlevel(userlevel);
            paramInfo.setViprebate(viprebate);
            paramInfo.setDelflag(delflag);

            // 更新用户信息
            int result = userService.editUserInfo(paramInfo);

            // 初期设定信息
            if (result == 1) {
                model.addFlashAttribute("status", "0");
            } else {
                model.addFlashAttribute("status", "1");
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("审核更新用户信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :",e);
            return SysConstant.ERROR_PAGE_500;
        }

        // 跳转界面
        return "userCenter";
    }

    /**
     *
     * @Description:获取后台详细用户审核信息
     * @param request
     * @return String
     */
    @RequestMapping("/getInfoRear")
    public String getInfoRear(HttpServletRequest request, Model model) {
        try {
            // 获取登录用户
            User sysUser = (User) request.getSession().getAttribute("User");

            if (CmnUtil.isEmpty(sysUser)) {
                return SysConstant.LOGIN_PAGE;
            }

            // 设定检索条件
            User paramInfo = new User();

            List<User> resultUser = userService.getAllUser(paramInfo);

            // 初期设定信息
            if (!CmnUtil.isEmpty(resultUser)) {
                model.addAttribute("baseUser", resultUser);
            } else {
                model.addAttribute("baseUser", null);
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("获取用户中心信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :",e);
            return SysConstant.ERROR_PAGE_500;
        }

        return "UserCenter";
    }
}
